<template>
  <div>
      <s-table :search-params="searchParams" :COLUMNS="columns" :async-fc="page" ref="table">
          <template #tableHeader>
              <t-button v-has-perms="['system:role:manage']"  @click="insert">新增信息</t-button>
          </template>
      </s-table>
      <t-dialog header="用户信息" v-model:visible="modalOpen" @confirm="onModalSubmit" width="50%" placement="center">
        <t-form ref="submitFormRef" :rules="FORM_RULES" :data="submitForm" >
          <t-row style="width: 100%" :gutter="[9,12]">
            <t-col :span="4">
              <t-form-item  :label="t('pages.sysUser.username')" name="username">
                <t-input v-model="submitForm.username" :placeholder="t('pages.sysUser.username')"/>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item v-show="!submitForm.id" :label="t('pages.sysUser.password')" name="password">
                <t-input v-model="submitForm.password" :placeholder="t('pages.sysUser.password')"/>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="性别" name="sex">
                <t-select v-model="submitForm.sex" :options="sexOptions" :placeholder="t('pages.sysUser.sex')">
                </t-select>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item :label="t('pages.sysUser.nickname')" name="nickname">
                <t-input v-model="submitForm.nickname" :placeholder="t('pages.sysUser.nickname')"/>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item :label="t('pages.sysUser.phone')" name="phone">
                <t-input v-model="submitForm.phone" :placeholder="t('pages.sysUser.phone')"/>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item :label="t('pages.sysUser.email')" name="email">
                <t-input v-model="submitForm.email" :placeholder="t('pages.sysUser.email')"/>
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item :label="t('pages.sysUser.role')" name="roles">
                <t-select v-model="submitForm.roles" multiple :options="roleOptions" :placeholder="t('pages.sysUser.rolePlaceholder')"/>
              </t-form-item>
              </t-col>
            <t-col :span="4" >
              <t-form-item :label="t('pages.sysUser.remarks')" name="remarks">
                <t-textarea  v-model="submitForm.remarks" :placeholder="t('pages.sysUser.remarksPlaceholder')"/>
              </t-form-item>
            </t-col>
            <t-col :span="4" >
              <t-form-item :label="t('pages.sysUser.avatar')" name="avatar" >
               <s-upload style="width: 500px;" v-model:value="submitForm.avatar" type="image" value-type="data" :limit="1" :tip="t('pages.sysUser.avatarPlaceholder')" />
              </t-form-item>
            </t-col>
          </t-row>
          </t-form>

      </t-dialog>
  </div>
</template>
<script setup lang="ts">
/*****                                          引用部分开始                                          *****/
import { onMounted, ref } from "vue";
import { t } from "@/locales";
import STable from '@/components/s-table/index.vue';
import SUpload from '@/components/s-upload/index.vue';
import { TableInstanceFunctions } from "@/components/s-table/type";
import { searchParams, COLUMNS, FORM_RULES, sexOptions } from "../userList/props/index";
import { page, update, insert as insertApi, deleteById, kickUserOut, resetPassword } from "@/api/sysUser";
import { FormInstanceFunctions, Link, Space, MessagePlugin, DialogPlugin, Option } from "tdesign-vue-next";
import { getOptions } from "@/api/sysRole";
import { Popconfirm } from "tdesign-vue-next";
/*****                                          引用部分结束                                          *****/


/*****                                          属性定义部分开始                                          *****/
const submitForm = ref({
  id:'',
  username:'',
  password:'',
  slat:'',
  sex:2,
  nickname:'',
  roles:[],
  phone:'',
  email:'',
  avatar:'',
  remarks:'',
  //添加所用到的字段
});
const roleOptions = ref([]);
const modalOpen = ref(false);
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<TableInstanceFunctions>(null);
/*****                                          属性定义部分结束                                          *****/


const columns = COLUMNS.concat([{
  align: 'left',
  fixed: 'right',
  colKey: 'op',
  width: 250,
  title: t('components.commonTable.operation'),
  cell: (h, slot:{row:any}) => h(Space, {}, [
      h(Link, {
          theme: 'primary',
          onClick: () => {
            slot.row.roles = slot.row.roles.map((i:any) => i.value);
              submitForm.value = slot.row;
              modalOpen.value = true;
          }
      }, '修改'),
      h(Link, {
          theme: 'danger',
          onClick: () => {
              const confirmDialog = DialogPlugin.confirm({
                  header: `提示`,
                  body: `删除后，标记为${slot.row.id}的所有信息将被清空，且无法恢复`,
                  confirmBtn: {
                      content: '提交',
                      theme: 'primary',
                      loading: false,
                  },
                  theme: 'warning',
                  onConfirm: async () => {
                      confirmDialog.update({ confirmBtn: { content: '提交中', loading: true } });
                      await deleteById(slot.row.id);
                      MessagePlugin.success('删除成功！');
                      table.value.onSearch();
                      confirmDialog.update({ confirmBtn: { content: '提交', loading: false } });
                      confirmDialog.hide();
                  },
              })
          }
      }, '删除'),
      h(Popconfirm, {
          content: `确定要踢出用户 ${slot.row.username} 吗？`,
          confirmBtn: {
              content: '踢出',
              theme: 'primary',
          },
          cancelBtn: {
              content: '取消',
              theme: 'default',
          },
          theme: 'warning',
          onConfirm: async () => {
              try {
                  await kickUserOut(slot.row.id);
                  MessagePlugin.success('用户已下线！');
              } catch (error) {
                  MessagePlugin.error('踢出用户失败: ' + error.message);
              }
          },
      }, {
          default: () => h(Link, {
              theme: 'warning',
          }, '踢出'),
      }),
      // 添加重置密码的链接
      h(Popconfirm, {
          content: `确定要重置用户 ${slot.row.username} 的密码吗？`,
          confirmBtn: {
              content: '重置',
              theme: 'primary',
          },
          cancelBtn: {
              content: '取消',
              theme: 'default',
          },
          theme: 'warning',
          onConfirm: async () => {
              try {
                  await resetPassword(slot.row.id);
                  MessagePlugin.success('密码重置成功！');
              } catch (error) {
                  MessagePlugin.error('重置密码失败: ' + error.message);
              }
          },
      }, {
          default: () => h(Link, {
              theme: 'warning',
          }, '重置密码'),
        }),
  ])
}]);


/*****                                          页面方法开始                                          *****/
const insert = () => {
  modalOpen.value = true;
  submitForm.value = {
    id: '',
    username: '',
    password: '',
    slat: '',
    sex: 2,
    nickname: '',
    roles:[],
    phone: '',
    email: '',
    avatar: '', 
    remarks: '',
  };
  if (submitFormRef.value) {
    submitFormRef.value.reset();
  }


}

/**
* 提交表单
*/
const onModalSubmit = async () => {
  const valid = await submitFormRef.value.validate();
      // 直接修改 role 属性
      submitForm.value = { 
      ...submitForm.value, 
      roles: submitForm.value.roles.map((i:any) => ({value:i})), } 
  if (valid === true) {

    if (submitForm.value.id) {
      await update(submitForm.value);
    } else {
      await insertApi(submitForm.value);
    }
    MessagePlugin.success('操作成功！');
    modalOpen.value = false;
    table.value.onSearch();
  }
}

onMounted(async() => {
  const data = await getOptions();
  roleOptions.value = data;
})
/*****                                          页面方法结束                                          *****/
</script>